// mainwindow.cpp
#include "mainwindow.h"
#include <QFile>
#include <QApplication>
#include <QTextStream>
#include <QScrollArea> // 添加 QScrollArea 头文件
#include <QDebug> // 添加 qDebug 用于调试
#include <QTimer>
#include <QRegularExpression>
#include <QRegularExpressionMatch>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), rng(std::random_device()()), dist(0, 99)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("C:/Users/33342/Desktop/ysgc/ysgc_database.db");
 //   db.setDatabaseName("home/lwj/project/ysgc/ysgc_database.db");
    linkserver();
     this->setWindowTitle("卫星数据"); // 设置窗口标题

    QWidget *centralWidget = new QWidget(this);
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
    mainLayout->setContentsMargins(10, 10, 10, 10); // 设置边距
    mainLayout->setSpacing(10); // 设置间距

    // 左侧div
    QWidget *leftDiv = new QWidget(centralWidget);
    leftDiv->setObjectName("leftDiv"); // 设置对象名称以便在样式表中引用
    QVBoxLayout *leftLayout = new QVBoxLayout(leftDiv); // 使用 QVBoxLayout 实现垂直排列
    leftLayout->setContentsMargins(0, 0, 0, 0); // 设置边距
    leftLayout->setSpacing(10); // 设置间距
    leftLayout->setAlignment(Qt::AlignTop); // 确保内部元素靠上

    // 顶部div
    QWidget *topDiv = new QWidget(leftDiv);
    topDiv->setObjectName("topDiv"); // 设置对象名称以便在样式表中引用
    QHBoxLayout *topLayout = new QHBoxLayout(topDiv); // 使用 QHBoxLayout 实现水平排列
    topLayout->setContentsMargins(0, 0, 0, 0); // 设置边距
    topLayout->setSpacing(10); // 设置间距
    topLayout->setAlignment(Qt::AlignTop); // 确保内部元素靠左

    // 小标题
    QLabel *boxTitle = new QLabel(topDiv);
    boxTitle->setText("卫星数据");
    boxTitle->setObjectName("boxTitle"); // 设置对象名称以便在样式表中引用
    topLayout->addWidget(boxTitle); // 添加到顶部div

    comboBox1 = new QComboBox(topDiv);
    comboBox1->addItem("BD");
    comboBox1->addItem("GPS");
    comboBox1->addItem("Galileo");

    comboBox2 = new QComboBox(topDiv);
    comboBox2->hide(); // 隐藏 comboBox2

    topLayout->addWidget(comboBox1);
    topLayout->addWidget(comboBox2);

    leftLayout->addWidget(topDiv); // 将 topDiv 添加到 leftLayout

    // 创建 midDiv 并设置布局
    QWidget *midDiv = new QWidget(leftDiv);
    midDiv->setObjectName("midDiv");
    QVBoxLayout *midLayout = new QVBoxLayout(midDiv);
    midLayout->setContentsMargins(0, 0, 0, 0);
    midLayout->setSpacing(5);

    // 创建 QScrollArea 和其内容窗口部件
    QScrollArea *scrollArea = new QScrollArea(midDiv);
    scrollArea->setWidgetResizable(true); // 确保内容窗口部件可以根据内容调整大小

    scrollContent = new QWidget();
    QVBoxLayout *buttonLayout = new QVBoxLayout(scrollContent);
    buttonLayout->setAlignment(Qt::AlignTop); // 按钮靠上对齐
    buttonLayout->setSpacing(5);

    scrollArea->setWidget(scrollContent);
    midLayout->addWidget(scrollArea);

    leftLayout->addWidget(midDiv); // 将 midDiv 添加到 leftLayout

    // 底部div
    QWidget *bottomDiv = new QWidget(leftDiv);
    bottomDiv->setObjectName("bottomDiv"); // 设置对象名称以便在样式表中引用
    QVBoxLayout *bottomLayout = new QVBoxLayout(bottomDiv); // 使用 QVBoxLayout 实现垂直排列
    bottomLayout->setContentsMargins(0, 0, 0, 0); // 设置边距
    bottomLayout->setSpacing(10); // 设置间距

    // 标题和清空按钮
    QWidget *titleButtonDiv = new QWidget(bottomDiv);
    QHBoxLayout *titleButtonLayout = new QHBoxLayout(titleButtonDiv); // 使用 QHBoxLayout 实现水平排列
    titleButtonLayout->setContentsMargins(0, 0, 0, 0); // 设置边距
    titleButtonLayout->setSpacing(10); // 设置间距
    titleButtonLayout->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // 确保内部元素靠左对齐并垂直居中

    QLabel *notificationTitle = new QLabel(titleButtonDiv);
    notificationTitle->setText("通知内容");
    notificationTitle->setObjectName("notificationTitle"); // 设置对象名称以便在样式表中引用
    titleButtonLayout->addWidget(notificationTitle); // 添加到标题和按钮div

    // 添加一个伸缩因子，把按钮推到右侧
    titleButtonLayout->addStretch();  // 使按钮靠右对齐

    QPushButton *clearButton = new QPushButton(titleButtonDiv);
    clearButton->setText("清空");
    clearButton->setObjectName("clearButton"); // 设置对象名称以便在样式表中引用
    titleButtonLayout->addWidget(clearButton); // 添加到标题和按钮div
    clearButton->hide(); // 隐藏清空按钮

    bottomLayout->addWidget(titleButtonDiv); // 将标题和按钮div 添加到底部div

    // 通知消息显示区域
    notificationsText = new QTextEdit(bottomDiv);
    notificationsText->setObjectName("notificationsText"); // 设置对象名称以便在样式表中引用
    notificationsText->setLineWrapMode(QTextEdit::NoWrap); // 不换行
    bottomLayout->addWidget(notificationsText); // 将通知消息显示区域添加到底部div

    leftLayout->addWidget(bottomDiv); // 将 bottomDiv 添加到 leftLayout
    leftLayout->setStretchFactor(topDiv, 1); // 顶部div 占据 10% 的高度
    leftLayout->setStretchFactor(midDiv, 5);
    leftLayout->setStretchFactor(bottomDiv, 4); // 底部div 占据 40% 的高度

    // 将 leftDiv 添加到主布局，并设置拉伸因子为 30%
    mainLayout->addWidget(leftDiv);
    leftDiv->setMaximumWidth(400); // 最大宽度为400像素
    mainLayout->setStretchFactor(leftDiv, 3);

    // 表格div
    tableWidget = new QTableWidget(centralWidget);

    tableWidget->setAlternatingRowColors(true); // 设置交替行颜色
    tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); // 确保水平滚动条始终显示

    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); // 禁止编辑

    // 将 tableWidget 添加到主布局，并设置拉伸因子为 70%
    mainLayout->addWidget(tableWidget);
    mainLayout->setStretchFactor(tableWidget, 7);

    centralWidget->setLayout(mainLayout);
    setCentralWidget(centralWidget);

    connect(comboBox1, SIGNAL(currentIndexChanged(int)), this, SLOT(updateSatelliteList()));
    connect(comboBox1, SIGNAL(currentIndexChanged(int)), this, SLOT(clearTableContents()));
    connect(comboBox2, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtonStyles()));
    connect(comboBox2, SIGNAL(currentIndexChanged(int)), this, SLOT(clearTableContents()));

    updateSatelliteList(); // 初始化时更新卫星列表
    loadStylesheet(); // 加载样式表

    // 设置窗口的默认宽度和高度
    this->resize(1200, 800); // 宽度为1200像素，高度为800像素

    satelliteHandler = new SatelliteHandler(tableWidget); // 初始化 SatelliteHandler

//    dataTimer = new QTimer(this); // 初始化定时器
//    connect(dataTimer, &QTimer::timeout, this, &MainWindow::receiveData); // 连接信号
//    dataTimer->start(100); // 每隔100毫秒触发一次
//    dataTimer->start(1000); // 每隔1000毫秒触发一次
}
void MainWindow::updateSatelliteList()
{
    QWidget *parent = scrollContent;
    updateTableHeaders(); // 更新表头

    // 获取当前布局
    QVBoxLayout *buttonLayout = qobject_cast<QVBoxLayout*>(parent->layout());

    // 确保布局有效并清除其中的按钮
    if (buttonLayout) {
        // 清除现有的按钮
        clearLayout(buttonLayout);
    }

    // 重新添加按钮
    QString source = comboBox1->currentText();

    if (source == "BD") {
//      qDebug() << "BD satellites: 42"; // Debug
        addSatelliteButtons("bd2",63); // 添加 63 个卫星按钮
    } else if (source == "GPS") {
//      qDebug() << "GPS satellites: 30"; // Debug
        addSatelliteButtons("gps",32); // 添加 32 个卫星按钮
    } else if (source == "Galileo") {
        addSatelliteButtons("gal",31); // 添加 31 个卫星按钮
    }

    updateButtonStyles(); // 更新按钮样式
}
// 处理按钮点击事件的槽函数
void MainWindow::onSatelliteButtonClicked(std::string name,int satelliteIndex)
{
    comboBox2->setCurrentIndex(satelliteIndex);  // 更改选项
    clearTableContents(); // 清空表格内容
    qDebug() << "Satellite button clicked:" << satelliteIndex; // Debug
    // 在这里实现按钮点击后要执行的操作
    if(name=="bd2"){
        if(satelliteIndex>=5 && satelliteIndex<=58) {
             read_sqlite_data("bd2meo", satelliteIndex); // 读取数据库数据并显示
        }
        else {
        read_sqlite_data("bd2geo", satelliteIndex); // 读取数据库数据并显示
        }
    }
    else if(name=="gps") {
        read_sqlite_data("gps", satelliteIndex); // 读取数据库数据并显示
    }
    else if(name=="gal") {
        read_sqlite_data("gal", satelliteIndex); // 读取数据库数据并显示
    }
    else if(name=="bd2全部") {
        read_everysqlite_data("bd2全部"); // 读取数据库数据并显示
    }
    else if(name=="gps全部") {
        read_everysqlite_data("gps全部"); // 读取数据库数据并显示
    }
    else if(name=="gal全部") {
        read_everysqlite_data("gal全部");
    }

}

void MainWindow::loadStylesheet()
{
    QFile file("../styles.css");
    if (file.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(file.readAll());
        qApp->setStyleSheet(styleSheet);
        file.close();
    }
}
void MainWindow::clearLayout(QLayout* layout)
{
    if (!layout) return;

    // 获取布局中的项目数量
    int count = layout->count();
    for (int i = count - 1; i >= 0; --i) {
        QLayoutItem* item = layout->takeAt(i);
        if (item->layout()) {
            // 如果是子布局，递归清除
            clearLayout(item->layout());
            delete item->layout(); // 清除并释放子布局
        }
        if (item->widget()) {
            // 如果是窗口部件，删除它
            delete item->widget();
        }
        delete item; // 删除布局项本身
    }
}
void MainWindow::updateButtonStyles() {
    // 获取当前 comboBox2 选中的索引
    int index = comboBox2->currentIndex();

    // 获取 scrollContent 中的布局（假设是 QVBoxLayout）
    QVBoxLayout *buttonLayout = qobject_cast<QVBoxLayout*>(scrollContent->layout());
    if (!buttonLayout) {
        qWarning() << "buttonLayout is null, make sure the layout is set correctly";
        return;
    }

    // 遍历所有的按钮并重置样式
    int buttonIndex = 0;
    for (int i = 0; i < buttonLayout->count(); ++i) {
        QWidget *widget = buttonLayout->itemAt(i)->widget();
        if (widget && qobject_cast<QPushButton*>(widget)) {
            QPushButton *button = qobject_cast<QPushButton*>(widget);

            // 重置按钮的样式
            button->setStyleSheet("");  // 清除现有样式（可以根据需要设置）

            QIcon icon("../config/satellite.png");
            button->setIcon(icon);
            button->setIconSize(QSize(16, 16));  // 设置图标大小

            // 如果当前按钮的索引和 comboBox2 中的索引匹配，更新样式
            if (buttonIndex == index) {
                button->setStyleSheet("QPushButton { background-color: #2980b9; color: white; }");
            }

            buttonIndex++;
        }
    }
}
void MainWindow::noticeMessage(int index,int satelliteID,QString source) {
    // 获取当前时间
    QString curTime = QDateTime::currentDateTime().toString("[yyyy-MM-dd HH:mm:ss]");
    notificationsText->append(QString(curTime + "接受到%1卫星（%2）数据...").arg(source).arg(satelliteID)); // 显示通知消息

    // 保证 notificationsText 最多只显示 200 行
    QStringList lines = notificationsText->toPlainText().split("\n");
    if (lines.size() > 200) {
        lines = lines.mid(lines.size() - 200); // 保留最后 200 行
        notificationsText->setPlainText(lines.join("\n"));
    }
}
void MainWindow::clearTableContents() {
//    qDebug() << "clearTableContents";
    tableWidget->clearContents();
}
void MainWindow::createSatelliteButtons(std::string name,int satelliteIndex) {
    QWidget *parent = scrollContent;
    QVBoxLayout *buttonLayout = qobject_cast<QVBoxLayout*>(parent->layout());

    if (satelliteIndex == 0) {
        comboBox2->clear();  // 清空现有选项
        comboBox2->addItem("全部");
        QPushButton *button = new QPushButton("全部", parent);
        buttonLayout->addWidget(button); // 将按钮添加到布局
        if(name=="bd2") {
            connect(button, &QPushButton::clicked, [this]() { onSatelliteButtonClicked("bd2全部",0);});
        }
        else if(name=="gps") {
            connect(button, &QPushButton::clicked, [this]() { onSatelliteButtonClicked("gps全部",0);});
        }
        else if(name=="gal") {
            connect(button, &QPushButton::clicked, [this]() { onSatelliteButtonClicked("gal全部",0);});
        }
        }
    else {
        // 添加到 comboBox
        comboBox2->addItem(QString("卫星%1").arg(satelliteIndex));

        // 创建按钮并添加到布局
        QPushButton *button = new QPushButton(QString("卫星%1").arg(satelliteIndex), parent);
        buttonLayout->addWidget(button);

        // 连接按钮点击信号到槽函数
        connect(button, &QPushButton::clicked, [this, satelliteIndex, name]() {
            onSatelliteButtonClicked(name,satelliteIndex);
        });
    }
}
void MainWindow::addSatelliteButtons(std::string name,int number) {
    for (int i = 0; i <= number; ++i) {
        createSatelliteButtons(name,i);
    }
}
void MainWindow::updateTableHeaders() {
    QString source = comboBox1->currentText();

    QString path = "config/" + source + "_config.ini";
    ConfigTableWidget configTableWidget(tableWidget);

    if (source == "BD") {
        configTableWidget.configureTable(path);
    } else if (source == "GPS") {
        configTableWidget.configureTable(path);
    } else if (source == "Galileo") {
        configTableWidget.configureTable(path);
    }
}
void MainWindow::receiveData(){
    QString source = comboBox1->currentText(); // 获取当前选择的卫星源
    int index = comboBox2->currentIndex(); // 获取当前选择的卫星索引
    int maxIndex = comboBox2->count(); // 获取最大索引

    //    qDebug() << "only display data - source:" << source << ", index:" << index; // Debug

    // DecoderBD2RAWEPHEMmeo_data data = satelliteHandler->readClientData(source); // 生成随机数据-old
    qDebug() << "读取客户端数据";
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket) {
        // 先读取表示结构体类型的整数
        int structType;
        socket->read((char *)&structType, sizeof(int));
        qDebug() << structType;
        if (structType == 1 && source == "BD") {
            DecoderBD2RAWEPHEMmeo_data data;
            socket->read((char *)&data, sizeof(DecoderBD2RAWEPHEMmeo_data));
            qDebug() << sizeof(data);
            noticeMessage(index,data.prn,source);
            if (index == 0 || index == data.prn)
                satelliteHandler->displaySatelliteDataBDmeo(data); // 显示BDmeo卫星数据
        }
        else if (structType == 2 && source == "BD") {
            DecoderBD2RAWEPHEMgeo_data data;
            socket->read((char *)&data, sizeof(DecoderBD2RAWEPHEMgeo_data));
            qDebug() << sizeof(data);
            noticeMessage(index,data.prn,source);

            if (index == 0 || index == data.prn)
                satelliteHandler->displaySatelliteDataBDgeo(data); // 显示BDgeo卫星数据
        }
        else if (structType == 3 && source == "Galileo") {//伽利略的暂时是Galileo
            GALephemeris_data data;

            socket->read((char *)&data, sizeof(GALephemeris_data));
            qDebug() << sizeof(data);

            noticeMessage(index,(int)data.satId,source);

            if (index == 0 || index == data.satId)
                satelliteHandler->displaySatelliteDataGAL(data); // 显示伽利略卫星数据
        }
        else if (structType == 4 && source == "GPS") {
            DecoderGPSRAWEPHEM_data data;
            socket->read((char *)&data, sizeof(DecoderGPSRAWEPHEM_data));
            noticeMessage(index,data.prn,source);
            qDebug() << sizeof(data);
            if (index == 0 || index == data.prn)
                satelliteHandler->displaySatelliteDataGPS(data); // 显示GPS卫星数据
        }
    }


    // if (index == 0 || index == data.prn) {
    //     // 获取当前时间
    //     QString curTime = QDateTime::currentDateTime().toString("[yyyy-MM-dd HH:mm:ss]");
    //     notificationsText->append(QString(curTime + "接受到卫星（%1）数据...").arg(data.prn)); // 显示通知消息
    //
    //     // 保证 notificationsText 最多只显示 200 行
    //     QStringList lines = notificationsText->toPlainText().split("\n");
    //     if (lines.size() > 200) {
    //         lines = lines.mid(lines.size() - 200); // 保留最后 200 行
    //         notificationsText->setPlainText(lines.join("\n"));
    //     }
    //
    //     satelliteHandler->displaySatelliteData(data); // 显示卫星数据-old
    // }
}

void MainWindow::handleNewConnection(){
    qDebug() << "连接到客户端";
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    if (clientSocket) {
        connect(clientSocket, &QTcpSocket::readyRead, this, &MainWindow::receiveData);


    }
}
void MainWindow::linkserver() {
    tcpServer = new QTcpServer(this);
    if (tcpServer->listen(QHostAddress::Any, 8888)) {
        tcpServer = new QTcpServer();
        if (tcpServer->listen(QHostAddress::LocalHost, 8080)) {  // 监听本地8080端口，与客户端对应
            qDebug() << "服务器启动，监听端口 8080";
            connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection);
        } else {
            qDebug() << "服务器启动失败";
        }
    }
}
void MainWindow::read_sqlite_data(QString name ,int prn) {
    if (!db.open()) {
        qDebug() << "无法打开数据库: " << db.lastError().text();
        db.close();
        return;
    }
    bool exists = tableExists(name,prn);
    if (exists) {
        QSqlQuery countQuery((creatsql("SELECT COUNT(*) FROM ?_ephem_data",name,prn)));
        if (countQuery.next()) {
            int totalRows = countQuery.value(0).toInt();
            //后续根据总行数确定查询逻辑
            QSqlQuery query;
            query.prepare(creatsql("SELECT * FROM ?_ephem_data ORDER BY rowid DESC LIMIT 24",name,prn));
            if (query.exec()) {
                if(name=="bd2geo") {
                        server_bd2geo_data(query);
                }
                else if(name=="bd2meo") {
                        server_bd2meo_data(query);
                }
                else if(name=="gal") {
                        server_gal_data(query);
                }
                else if(name=="gps") {
                        server_gps_data(query);
                }
            } else {
                qDebug() << "查询数据失败: " << query.lastError().text();
            }
            db.close();
        } else {
            qDebug() << "获取行数失败: " << countQuery.lastError().text();
        }
    }
    db.close();
}
void MainWindow::read_everysqlite_data(QString name) {
    if (!db.open()) {
        qDebug() << "无法打开数据库: " << db.lastError().text();
         db.close();
        return;
    }
    if(name=="bd2全部") {
        for(int i=64;i>0;i--) {
            if(i>4&&i<59) {
                if(!sever_all_data("bd2meo",i)) {
                    qDebug() << "bd2meo"<<i<<"不存在";
                }
            }
            else {
                if(!sever_all_data("bd2geo",i)) {
                    qDebug() << "bd2geo"<<i<<"不存在";
                }
            }
        }
    }
    else if(name=="gps全部") {
        for(int i=32;i>0;i--) {
            if(!sever_all_data("gps",i)) {
                qDebug() << "gps"<<i<<"不存在";
            }
        }
    }
    else if(name=="gal全部") {
        for(int i=32;i>0;i--) {
            if(!sever_all_data("gal",i)) {
                qDebug() << "gal"<<i<<"不存在";
            }
        }
    }
    db.close();
}
QString MainWindow::creatsql(QString sql, QString name, int prn) {
    QString str_num = QString::number(prn);
    QString replaceStr = name + str_num;
    int pos = sql.indexOf("?");
    if (pos!= -1) {
        // 获取要替换掉的目标字符串 "????" 的长度，这里固定为4
        QString target = "?";
        int targetLen = target.length();
        // 替换操作，从找到的位置pos开始，替换长度为targetLen，替换内容为replaceStr
        sql.remove(pos, targetLen);
        sql.insert(pos, replaceStr);
    }
    return sql;
}
void MainWindow::server_bd2geo_data(QSqlQuery query) {
    DecoderBD2RAWEPHEMgeo_data data[24];
    int i=0;
    while(query.next()) {
        QString timeStr = query.value(0).toString();
        strcpy(data[i].time, timeStr.toStdString().c_str());
        data[i].prn = query.value(1).toInt();
        data[i].refWeek = query.value(2).toInt();
        data[i].refSecs = query.value(3).toInt();
        data[i].SatH1 = query.value(4).toUInt();
        data[i].AODC = query.value(5).toUInt();
        data[i].URA = query.value(6).toDouble();
        data[i].WN = query.value(7).toUInt();
        data[i].toc = query.value(8).toDouble();
        data[i].TGD1 = query.value(9).toUInt();
        data[i].TGD2 = query.value(10).toUInt();
        data[i].alpha0 = query.value(11).toDouble();
        data[i].alpha1 = query.value(12).toDouble();
        data[i].alpha2 = query.value(13).toDouble();
        data[i].alpha3 = query.value(14).toDouble();
        data[i].beta0 = query.value(15).toDouble();
        data[i].beta1 = query.value(16).toDouble();
        data[i].beta2 = query.value(17).toDouble();
        data[i].beta3 = query.value(18).toDouble();
        data[i].a0 = query.value(19).toDouble();
        data[i].a1 = query.value(20).toDouble();
        data[i].a2 = query.value(21).toDouble();
        data[i].AODE = query.value(22).toUInt();
        data[i].deltaN = query.value(23).toUInt();
        data[i].Cuc = query.value(24).toDouble();
        data[i].M0 = query.value(25).toDouble();
        data[i].Cus = query.value(26).toDouble();
        data[i].e = query.value(27).toDouble();
        data[i].A = query.value(28).toDouble();
        data[i].Cic = query.value(29).toDouble();
        data[i].Cis = query.value(30).toDouble();
        data[i].toe = query.value(31).toUInt();
        data[i].i0 = query.value(32).toDouble();
        data[i].Crc = query.value(33).toDouble();
        data[i].Crs = query.value(34).toDouble();
        data[i].Omega = query.value(35).toDouble();
        data[i].Omega0 = query.value(36).toDouble();
        data[i].w = query.value(37).toDouble();
        data[i].IDOT = query.value(38).toDouble();
        i++;
    }
    for(i--;i>=0;i--) {
         satelliteHandler->displaySatelliteDataBDgeo(data[i]);
    }
}
void MainWindow::server_bd2meo_data(QSqlQuery query) {
     DecoderBD2RAWEPHEMmeo_data data[24];
    int i=0;
    while (query.next())
    {
            QString timeStr = query.value(0).toString();
            strcpy(data[i].time, timeStr.toStdString().c_str());
            data[i].prn = query.value(1).toInt();
            data[i].refWeek = query.value(2).toInt();
            data[i].refSecs = query.value(3).toInt();
            data[i].SatH1 = query.value(4).toUInt();  // 这里应该转换为无符号整数类型更合适，因为定义中是uint8_t
            data[i].AODC = query.value(5).toUInt();
            data[i].URA = query.value(6).toDouble();
            data[i].WN = query.value(7).toUInt();
            data[i].toc = query.value(8).toDouble();
            data[i].TGD1 = query.value(9).toUInt();
            data[i].TGD2 = query.value(10).toUInt();
            data[i].alpha0 = query.value(11).toDouble();
            data[i].alpha1 = query.value(12).toDouble();
            data[i].alpha2 = query.value(13).toDouble();
            data[i].alpha3 = query.value(14).toDouble();
            data[i].beta0 = query.value(15).toDouble();
            data[i].beta1 = query.value(16).toDouble();
            data[i].beta2 = query.value(17).toDouble();
            data[i].beta3 = query.value(18).toDouble();
            data[i].a0 = query.value(19).toDouble();
            data[i].a1 = query.value(20).toDouble();
            data[i].a2 = query.value(21).toDouble();
            data[i].AODE = query.value(22).toUInt();
            data[i].deltaN = query.value(23).toUInt();
            data[i].Cuc = query.value(24).toDouble();
            data[i].M0 = query.value(25).toDouble();
            data[i].Cus = query.value(26).toDouble();
            data[i].e = query.value(27).toDouble();
            data[i].A = query.value(28).toDouble();
            data[i].Cic = query.value(29).toDouble();
            data[i].Cis = query.value(30).toDouble();
            data[i].toe = query.value(31).toUInt();
            data[i].i0 = query.value(32).toDouble();
            data[i].Crc = query.value(33).toDouble();
            data[i].Crs = query.value(34).toDouble();
            data[i].Omega = query.value(35).toDouble();
            data[i].Omega0 = query.value(36).toDouble();
            data[i].w = query.value(37).toDouble();
            data[i].IDOT = query.value(38).toDouble();
        i++;
    }
    for(i--;i>=0;i--) {
        satelliteHandler->displaySatelliteDataBDmeo(data[i]);
    }

}
void MainWindow::server_gal_data(QSqlQuery query) {
    GALephemeris_data data[24];
    int i=0;
    while (query.next()) {
        QString timeStr = query.value(0).toString();
        strcpy(data[i].time, timeStr.toStdString().c_str());
        double rawSatIdValue = query.value(1).toDouble();
        if (rawSatIdValue < 1) {
            data[i].satId = 1;
        } else if (rawSatIdValue > 36) {
            data[i].satId = 36;
        } else {
            data[i].satId = rawSatIdValue;
        }
    data[i].FNAVReceived = query.value(2).toDouble();
    data[i].INAVReceived = query.value(3).toDouble();
    data[i].E1BHealth = query.value(4).toDouble();
    data[i].E5aHealth = query.value(5).toDouble();
    data[i].E5bHealth = query.value(6).toDouble();
    data[i].E1BDVS = query.value(7).toDouble();
    data[i].E5aDVS = query.value(8).toDouble();
    data[i].E5bDVS = query.value(9).toDouble();
    data[i].SISA = query.value(10).toDouble();
    data[i].Reserved = query.value(11).toDouble();
    data[i].IODNav = query.value(12).toDouble();
    data[i].T0e = query.value(13).toDouble();
    data[i].RootA = query.value(14).toDouble();
    data[i].DeltaN = query.value(15).toDouble();
    data[i].M0 = query.value(16).toDouble();
    data[i].Ecc = query.value(17).toDouble();
    data[i].Omega = query.value(18).toDouble();
    data[i].Cuc = query.value(19).toDouble();
    data[i].Cus = query.value(20).toDouble();
    data[i].Crc = query.value(21).toDouble();
    data[i].Crs = query.value(22).toDouble();
    data[i].Cic = query.value(23).toDouble();
    data[i].Cis = query.value(24).toDouble();
    data[i].I0 = query.value(25).toDouble();
    data[i].IDot = query.value(26).toDouble();
    data[i].Omega0 = query.value(27).toDouble();
    data[i].OmegaDot = query.value(28).toDouble();
    data[i].FNAVT0c = query.value(29).toDouble();
    data[i].FNAVAf0 = query.value(30).toDouble();
    data[i].FNAVAf1 = query.value(31).toDouble();
    data[i].FNAVAf2 = query.value(32).toDouble();
    data[i].INAVT0c = query.value(33).toDouble();
    data[i].INAVAf0 = query.value(34).toDouble();
    data[i].INAVAf1 = query.value(35).toDouble();
    data[i].INAVAf2 = query.value(36).toDouble();
    data[i].E1E5aBGD = query.value(37).toDouble();
    data[i].E1E5bBGD = query.value(38).toDouble();
        i++;
    }
    for(i--;i>=0;i--) {
         satelliteHandler->displaySatelliteDataGAL(data[i]);
    }
}
void MainWindow::server_gps_data(QSqlQuery query) {
    DecoderGPSRAWEPHEM_data data[24];
    int i=0;
    while (query.next()) {
        QString timeStr = query.value(0).toString();
        strcpy(data[i].time, timeStr.toStdString().c_str());
        data[i].prn = query.value(1).toInt();
        data[i].refWeek =(query.value(2).toInt());
        data[i].refSecs = query.value(3).toInt();
        data[i].WN= query.value(4).toUInt();
        data[i].PCA= query.value(5).toUInt();
        data[i].URA= query.value(6).toUInt();
        data[i].SatH1= query.value(7).toUInt();
        data[i].IODC= query.value(8).toUInt();
        data[i].P= query.value(9).toUInt();
        data[i].TGD= query.value(10).toUInt();
        data[i].toc = query.value(11).toDouble();
        data[i].af2 = query.value(12).toDouble();
        data[i].af1 = query.value(13).toDouble();
        data[i].af0 = query.value(14).toDouble();
        data[i].IODE = query.value(15).toDouble();
        data[i].Crs = query.value(16).toDouble();
        data[i].deltaN = query.value(17).toDouble();
        data[i].M0 = query.value(18).toDouble();
        data[i].Cuc = query.value(19).toDouble();
        data[i].e = query.value(20).toDouble();
        data[i].Cus = query.value(21).toDouble();
        data[i].A = query.value(22).toDouble();
        data[i].toe = query.value(23).toDouble();
        data[i].FIT = query.value(24).toDouble();
        data[i].AODO = query.value(25).toDouble();
        data[i].Cic = query.value(26).toDouble();
        data[i].Omega0 = query.value(27).toDouble();
        data[i].Cis = query.value(28).toDouble();
        data[i].i0 = query.value(29).toDouble();
        data[i].Crc = query.value(30).toDouble();
        data[i].w = query.value(31).toDouble();
        data[i].Omega = query.value(32).toDouble();
        data[i].IDOE = query.value(33).toDouble();
        data[i].IDOT = query.value(34).toDouble();
        i++;
    }
    for(i--;i>=0;i--) {
         satelliteHandler->displaySatelliteDataGPS(data[i]);
    }
}
bool MainWindow::sever_all_data(QString name,int prn) {
    bool exists = tableExists(name,prn);
    if (exists) {
        QSqlQuery query;
        query.prepare(creatsql("SELECT * FROM ?_ephem_data ORDER BY rowid DESC LIMIT 1",name,prn));;
        if (query.exec()) {
            if(name == "bd2meo") {
                server_bd2meo_data(query);
            }
            else if(name == "bd2geo") {
                server_bd2geo_data(query);
            }
            else if(name == "gal") {
                server_gal_data(query);
            }
            else if(name == "gps") {
                server_gps_data(query);
            }
            return 1;
        }
        else {
           return 0;
        }
    }
}
bool MainWindow::tableExists( QString name,int prn) {
    QSqlQuery query(db);
    QString sql=creatsql("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='?_ephem_data'",name,prn);
    // 执行查询语句
    if (query.exec(sql)) {
        if (query.next()) {
            int count = query.value(0).toInt();
            return count > 0;
        }
    }
    // 如果查询执行失败或者没有符合条件的结果，返回表不存在
    return false;
}
